const express = require('express');
const cors = require('cors');
const { initDatabase } = require('./database');
const setupTaskRoutes = require('./tasks');
const setupNoteRoutes = require('./notes');
const setupSettingsRoutes = require('./settings');

// 创建Express应用
const app = express();
const PORT = process.env.PORT || 3000;

// 配置中间件
app.use(cors()); // 允许所有跨域请求
app.use(express.json()); // 解析JSON请求体
app.use(express.urlencoded({ extended: true })); // 解析URL编码的请求体

// 初始化数据库
const db = initDatabase();

// 健康检查接口
app.get('/api/health', (req, res) => {
    res.json({
        status: 'ok',
        message: '服务器运行正常',
        timestamp: new Date().toISOString()
    });
});

// 设置API路由
const apiRouter = express.Router();

// 注册任务相关路由
apiRouter.use('/tasks', setupTaskRoutes(db));

// 注册笔记相关路由
apiRouter.use('/notes', setupNoteRoutes(db));

// 注册设置相关路由
apiRouter.use('/settings', setupSettingsRoutes(db));

// 数据迁移接口 - 从localStorage迁移数据到数据库
apiRouter.post('/migrate', (req, res) => {
    const { tasks: localStorageTasks, notes: localStorageNotes } = req.body;
    
    if (!localStorageTasks && !localStorageNotes) {
        return res.status(400).json({ error: '没有提供要迁移的数据' });
    }

    // 开始事务
    db.serialize(() => {
        db.run('BEGIN TRANSACTION');
        
        let hasError = false;
        let errorMessage = '';
        
        // 迁移任务数据
        if (Array.isArray(localStorageTasks) && localStorageTasks.length > 0) {
            const taskStmt = db.prepare('INSERT INTO tasks (id, text, completed, priority, created_at, is_daily) VALUES (?, ?, ?, ?, ?, ?)');
            
            localStorageTasks.forEach(task => {
                if (!hasError) {
                    try {
                        taskStmt.run(
                            task.id, 
                            task.text, 
                            task.completed ? 1 : 0, 
                            task.priority || 'medium', 
                            task.createdAt || new Date().toISOString(),
                            task.isDaily ? 1 : 0
                        );
                    } catch (err) {
                        hasError = true;
                        errorMessage = '任务数据迁移失败: ' + err.message;
                    }
                }
            });
            
            taskStmt.finalize();
        }
        
        // 迁移笔记数据
        if (Array.isArray(localStorageNotes) && localStorageNotes.length > 0 && !hasError) {
            const noteStmt = db.prepare('INSERT INTO notes (id, title, content, category, tags, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)');
            
            localStorageNotes.forEach(note => {
                if (!hasError) {
                    try {
                        noteStmt.run(
                            note.id, 
                            note.title, 
                            note.content, 
                            note.category || '快速笔记', 
                            note.tags ? JSON.stringify(note.tags) : '[]', 
                            note.createdAt || new Date().toISOString(),
                            note.updatedAt || new Date().toISOString()
                        );
                    } catch (err) {
                        hasError = true;
                        errorMessage = '笔记数据迁移失败: ' + err.message;
                    }
                }
            });
            
            noteStmt.finalize();
        }
        
        if (hasError) {
            db.run('ROLLBACK');
            res.status(500).json({ error: errorMessage });
        } else {
            db.run('COMMIT');
            res.json({ 
                success: true, 
                message: '数据迁移成功',
                migrated: {
                    tasks: Array.isArray(localStorageTasks) ? localStorageTasks.length : 0,
                    notes: Array.isArray(localStorageNotes) ? localStorageNotes.length : 0
                }
            });
        }
    });
});

// 使用API路由
app.use('/api', apiRouter);

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error('服务器错误:', err.stack);
    res.status(500).json({ 
        error: '服务器内部错误',
        message: err.message || '未知错误'
    });
});

// 404 处理中间件
app.use((req, res, next) => {
    res.status(404).json({ error: '请求的资源不存在' });
});

// 启动服务器
const server = app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log(`API 文档: http://localhost:${PORT}/api/health`);
    console.log(`任务API: http://localhost:${PORT}/api/tasks`);
    console.log(`笔记API: http://localhost:${PORT}/api/notes`);
    console.log(`设置API: http://localhost:${PORT}/api/settings`);
    console.log(`数据迁移API: http://localhost:${PORT}/api/migrate`);
});

// 优雅关闭服务器
process.on('SIGTERM', () => {
    console.log('收到终止信号，正在关闭服务器...');
    server.close(() => {
        console.log('服务器已关闭');
        db.close((err) => {
            if (err) {
                console.error('数据库关闭错误:', err.message);
            } else {
                console.log('数据库连接已关闭');
            }
            process.exit(0);
        });
    });
});